package com.wan37.auth.dao.impl;

import com.wan37.auth.dao.UserDao;
import com.wan37.auth.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author : luoyong
 * @date : 2020-06-01 16:50
 **/
@Transactional(propagation = Propagation.SUPPORTS, readOnly = false, rollbackFor = Exception.class)
@Repository
public class UserDaoImpl implements UserDao {

    @Autowired
    HibernateTemplate hibernateTemplate;

    @Override
    public boolean add(User user) {
        try {
            hibernateTemplate.save(user);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean delete(String userId) {
        try {
            hibernateTemplate.delete(userId);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public boolean update(User user) {
        try {
            hibernateTemplate.update(user);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public User getUserByUserId(String userId) {
        List<User> list = (List<User>) hibernateTemplate.find("from User where userId = ?", userId);
        if (!list.isEmpty()) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public List<User> getAllUsers() {

        List<User> list = (List<User>) hibernateTemplate.find("from User");
        if (!list.isEmpty()) {
            return list;
        }
        return null;
    }
}
